package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.ModifyNicknameContract;
import com.jtech.together.util.BmobUtil;
import com.jtech.together.view.activity.ModifyNicknameActivity;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 修改昵称
 * Created by wuxubaiyang on 2017/5/17.
 */
public class ModifyNicknamePresenter implements ModifyNicknameContract.Presenter {
    private Context context;
    private ModifyNicknameContract.View view;
    private String defaultNickname;

    public ModifyNicknamePresenter(Context context, ModifyNicknameContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
        //获取参数
        if (null != bundle) {
            this.defaultNickname = bundle.getString(ModifyNicknameActivity.KEY_DEFAULT_NICKNAME, "");
        }
    }

    @Override
    public String getDefaultNickname() {
        return defaultNickname;
    }

    @Override
    public void updateNickname(final String nickname) {
        final UserModel userModel = UserManager.getCurrentUser();
        userModel.setNickname(nickname);
        userModel.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    view.updateSuccess(nickname);
                    //更新本地即时通讯的用户表
                    UserManager.updateIMUserInfo(userModel);
                } else {
                    if (e.getErrorCode() == 401) {
                        view.updateFail("昵称已存在");
                    } else {
                        view.updateFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                    }
                }
            }
        });
    }
}